import sensor, image, time, network, usocket, sys
from pyb import UART,LED

#阈值
THRESHOLD = (43, 94, -83, -33, -4, 80)

#roil
roil = (8,8,190,190)

#uart初始化
uart = UART(3,115200)
uart.init(115200, bits=8, parity=None, stop=1)

#WiFi设置
SSID ='OPENMV_AP'    # Network SSID
KEY  ='1234567890'   # wifi密码(必须为10字符)
HOST = ''           # 使用第一个可用的端口
PORT = 8080         # 任意非特权端口

#摄像头初始化
sensor.reset()                      # Reset and initialize the sensor.
sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA)   # Set frame size to QVGA (320x240)
sensor.set_windowing(200,200)
sensor.set_vflip(True)
#sensor.set_hmirror(True)
sensor.set_transpose(True)

# 在AP模式下启动wlan模块。
wlan = network.WINC(mode=network.WINC.MODE_AP)
wlan.start_ap(SSID, key=KEY, security=wlan.WEP, channel=2)

#您可以阻止等待客户端连接
#   print(wlan.wait_for_sta(10000))

#找出返回色块列表中最大色块
def findMaxBlob(blobs):
    MaxSize = 0
    for blob in blobs:
            if blob[2]*blob[3] >= MaxSize:
                MaxSize = blob[2]*blob[3]
                MaxBlob = blob
    return MaxBlob

#数据打包
def outuart(x,y):
    global uart
    #发送数据
    uart.write('@')
    uart.write(str(x))
    uart.write(',')
    uart.write(str(y))
    uart.write(',')
    uart.write('\r\n')

def start_streaming(s):
    print ('Waiting for connections..')
    client, addr = s.accept()
    # 将客户端套接字超时设置为2秒
    client.settimeout(2.0)
    print ('Connected to ' + addr[0] + ':' + str(addr[1]))

    # 从客户端读取请求
    data = client.recv(1024)
    # 应该在这里解析客户端请求

    # 发送多部分head
    client.send("HTTP/1.1 200 OK\r\n" \
                "Server: OpenMV\r\n" \
                "Content-Type: multipart/x-mixed-replace;boundary=openmv\r\n" \
                "Cache-Control: no-cache\r\n" \
                "Pragma: no-cache\r\n\r\n")

    # FPS clock
    clock = time.clock()

    # 开始流媒体图像
    #注：禁用IDE预览以增加流式FPS。
    while (True):

        #写入你的代码
        clock.tick() # 跟踪snapshots()之间经过的毫秒数。
        img = sensor.snapshot()
        img.draw_rectangle(roil, color=(255,0,0))
        blobs=img.find_blobs([THRESHOLD], roi=roil)
        if blobs:
            MaxBlob = findMaxBlob(blobs)
            img.draw_rectangle(MaxBlob.rect())
            img.draw_cross(MaxBlob.cx(), MaxBlob.cy())
            print('x = '+str (MaxBlob.cx()), 'y = '+str (MaxBlob.cy()))
            outuart(MaxBlob.cx(),MaxBlob.cy())
        else:
            pass

        #写入你的代码

        cframe = img.compressed(quality=35)
        header = "\r\n--openmv\r\n" \
                 "Content-Type: image/jpeg\r\n"\
                 "Content-Length:"+str(cframe.size())+"\r\n\r\n"
        client.send(header)
        client.send(cframe)
        #@print(clock.fps())

while (True):
    # 创建服务器套接字
    s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    try:
        Bind and listen
        s.bind([HOST, PORT])
        s.listen(5)

        # 设置服务器套接字超时
        # 注意：由于WINC FW bug，如果客户端断开连接，服务器套接字必须
        # 关闭并重新打开。在这里使用超时关闭并重新创建套接字。
        s.settimeout(3)
        start_streaming(s)
        except OSError as e:
        s.close()
        print("socket error: ", e)
        sys.print_exception(e)
